import xlrd
import random
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
import utils

# 1.读取excel
data = xlrd.open_workbook('../myFile/data3.xlsx')
sheet = data.sheet_by_index(0)  # 获取工作表


class Question:
    pass


# 生成试题列表(乱序)
def create_question():
    question_list = []
    for index in range(sheet.nrows):
        if index > 1:
            obj = Question()
            obj.subject = sheet.cell(index, 1).value  # 题目
            obj.questionType = sheet.cell(index, 2).value  # 题型
            obj.option = []
            obj.option.append(sheet.cell(index, 3).value)
            obj.option.append(sheet.cell(index, 4).value)
            obj.option.append(sheet.cell(index, 5).value)
            obj.option.append(sheet.cell(index, 6).value)
            obj.score = sheet.cell(index, 7).value  # 分值
            question_list.append(obj)
    random.shuffle(question_list)  # 将序列所有元素随机排序
    return question_list


# 生成word试卷
def create_paper(file_name, paper_name, question_list):
    document = Document()
    # 页眉
    section = document.sections[0]
    header = section.header
    p1 = header.paragraphs[0]
    p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p1.text = paper_name
    # 页脚
    footer = section.footer
    p2 = footer.paragraphs[0]
    p2.text = "内部试题,禁止泄露"
    p2.alignment = WD_ALIGN_PARAGRAPH.CENTER
    # 试卷基本信息
    title = document.add_heading(paper_name, level=1)
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p3 = document.add_paragraph()
    p3.add_run('姓名:_____________  ')
    p3.add_run('  所属部门:_____________')
    p3.alignment = WD_ALIGN_PARAGRAPH.CENTER
    # 试题信息
    for question in question_list:
        subject = document.add_paragraph(style='List Number')
        run = subject.add_run(question.subject)
        run.bold = True  # 加粗
        subject.add_run('[%s]' % str(question.score))
        random.shuffle(question.option)  # 打乱选项顺序
        for index, option in enumerate(question.option):
            document.add_paragraph('ABCD'[index] + str(option))
    document.save(file_name)


targetPath = utils.get_project_root_abs_path() + '/myFile/wordProject/paper'  # 生成的文件存放目录
for i in range(3):
    questionList = create_question()
    fileName = targetPath + str(i + 1) + '.docx'
    create_paper(fileName, '2023年第一次模拟考', questionList)
